///////////////////////////////////////////////////////////////////////////////
//
//
//
///////////////////////////////////////////////////////////////////////////////

package view {

    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.net.FileReference;

    import model.UserProxy;

    import model.vo.LogRecord;
    import model.vo.UserVO;

    import mx.formatters.DateFormatter;

    import org.kolonitsky.alexey.debug.DebugWrapper;

    import org.puremvc.as3.interfaces.INotification;
    import org.puremvc.as3.patterns.mediator.Mediator;

    import view.events.DataSetEvent;
    import view.screens.LogScreen;

    /**
     * @author: akolonitsky
     * @date: 11/29/11 10:28 AM
     */
    public class ExportMediator extends Mediator
{
    public static const NAME:String = "exportMediator";

    public function ExportMediator(screen:LogScreen)
    {
        super(NAME, screen)
    }

    public function get screen():LogScreen
    {
        return viewComponent as LogScreen;
    }


    //-------------------------------------------------------------------------
    //
    //  Override mediator
    //
    //-------------------------------------------------------------------------

    override public function onRegister():void
    {
        super.onRegister();
        dateFormatter = new DateFormatter();
        dateFormatter.formatString = "YYYY-MM-DD";

        screen.addEventListener(DataSetEvent.EXPORT, app_exportHandler);

        sendNotification(AppFacade.USER_AUTHORIZATION);
    }

    override public function onRemove():void
    {
        screen.removeEventListener(DataSetEvent.EXPORT, app_exportHandler);
        super.onRemove();
    }

    override public function listNotificationInterests():Array
    {
        return [
            UserProxy.USER_AUTHORIZATION
        ];
    }

    override public function handleNotification(notification:INotification):void
    {
        super.handleNotification(notification);
        switch (notification.getName())
        {
            case UserProxy.USER_AUTHORIZATION:
            {
                if (notification.getBody())
                    user = notification.getBody() as UserVO;
                break;
            }
        }
    }




    //-------------------------------------------------------------------------
    //
    // Private logic
    //
    //-------------------------------------------------------------------------

    private var dateFormatter:DateFormatter = null;

    private var user:UserVO = null;
    private var currencies:Array = [];

    /**
     * Crate the CSV file from array of LogRecrod
     *
     * @param array of LogRecord which exported to external file.
     */
    private function exportToCSV(array:Array):void
    {
        var csv:String = "";

        currencies = [];
        for (var p:String in user.usedCurrencies)
            currencies.push(p)

        for each (var record:LogRecord in array)
            csv += recordToCSV(record);

        var headLine:String = "Дата, Комментарий," + currencies.join(",") + "\n";
        csv = headLine + csv;

        var fr:FileReference = new FileReference();
        fr.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        fr.addEventListener(Event.COMPLETE, fr_completeHandler);
        fr.addEventListener(Event.CANCEL, fr_completeHandler);
        fr.save(csv,  "home-accounting.csv");
    }

    /**
     * Convert the Log Record to CSV line
     *
     * @param record
     * @return
     */
    private function recordToCSV(record:LogRecord):String
    {
        var result:String = "";
        result += dateFormatter.format(record.date) + ",\"";
        result += record.comment + "\",";

        var currency:String = "";

        for (var i:int = 0; i < currencies.length; i++)
        {
            currency = currencies[i];
            result += currency in record.value ? record.value[currency] + "," : ",";
        }

        return result + "\n";
    }


    //-------------------------------------------------------------------------
    // Event handlers
    //-------------------------------------------------------------------------

    private function app_exportHandler(event:DataSetEvent):void
    {
        exportToCSV(event.dataSet);
    }

    private function ioErrorHandler(event:IOErrorEvent):void
    {
        DebugWrapper.trace(event.text);
    }

    private function fr_completeHandler(event:Event):void
    {
    }


}
}
